#!/bin/sh

# 配置参数
PROJECT_DIR="/storage/autocover"
FONT_PATH="${PROJECT_DIR}/fonts"
PYTHON_SCRIPT="${PROJECT_DIR}/main.py"
AUTOSTART_FILE="/storage/.config/autostart.sh"
SUPPORTED_SKINS="skin.confluence.minsk"
LOG_FILE="${PROJECT_DIR}/autocover.log"
DEPENDENCY_MARKER="${PROJECT_DIR}/.dependencies_installed"  # 依赖安装标记

# 依赖项定义
REQUIRED_PACKAGES="
    /opt/bin/opkg
    /opt/bin/python3
    /opt/bin/pip3
"

REQUIRED_PYTHON_LIBS="
    requests
    pillow
    watchdog
"

# 日志函数
log() {
    local level=$1
    local message=$2
    local timestamp=$(date +"%Y-%m-%d %H:%M:%S")
    
    # 确保日志目录存在
    mkdir -p "$(dirname "$LOG_FILE")"
    
    # 输出到日志文件
    echo "[$timestamp] [$level] $message" >> "$LOG_FILE"
    
    # 输出到控制台（根据级别设置颜色）
    case "$level" in
        INFO)
            echo -e "\033[32m[INFO] $message\033[0m"
            ;;
        WARNING)
            echo -e "\033[33m[WARNING] $message\033[0m"
            ;;
        ERROR)
            echo -e "\033[31m[ERROR] $message\033[0m"
            ;;
        DEBUG)
            echo -e "\033[36m[DEBUG] $message\033[0m"
            ;;
        *)
            echo "[$level] $message"
            ;;
    esac
}

# 错误处理函数
handle_error() {
    log ERROR "发生错误，脚本终止！错误详情：$1"
    echo -e "\n按回车键退出..."
    read
    exit 1
}

# 界面绘制函数
draw_interface() {
    clear
    # 上部：LOGO和标题
    echo -e "\033[34m
  ██████╗ ██████╗ ██████╗ ███████╗███████╗██╗     ███████╗ ██████╗
 ██╔════╝██╔═══██╗██╔══██╗██╔════╝██╔════╝██║     ██╔════╝██╔════╝
 ██║     ██║   ██║██████╔╝█████╗  █████╗  ██║     █████╗  ██║     
 ██║     ██║   ██║██╔══██╗██╔══╝  ██╔══╝  ██║     ██╔══╝  ██║     
 ╚██████╗╚██████╔╝██║  ██║███████╗███████╗███████╗███████╗╚██████╗
  ╚═════╝ ╚═════╝ ╚═╝  ╚═╝╚══════╝╚══════╝╚══════╝╚══════╝ ╚═════╝
\033[0m"
    echo -e "\033[32mCoreELEC Kodi收藏夹封面自动生成脚本 v1.3\033[0m"
    echo "========================================================"
}

# 配置国内镜像源
configure_mirrors() {
    log INFO "配置pip国内镜像源..."
    mkdir -p /storage/.pip
    cat > /storage/.pip/pip.conf <<EOF
[global]
index-url = https://mirrors.aliyun.com/pypi/simple/
trusted-host = mirrors.aliyun.com
EOF
}

# 安装Entware
install_entware() {
    log INFO "开始安装Entware..."
    
    if [ -x /opt/bin/opkg ]; then
        log INFO "Entware已安装，跳过"
        return 0
    fi
    
    log INFO "调用系统命令安装Entware..."
    if ! installentware; then
        log ERROR "Entware安装失败"
        return 1
    fi
    
    log INFO "Entware安装完成"
    return 0
}

# 检查Python库是否安装
check_python_library() {
    local library=$1
    local import_name=$1
    
    # 特殊处理Pillow库
    if [ "$library" = "pillow" ]; then
        import_name="PIL"
    fi
    
    log DEBUG "检查Python库: $library (导入名: $import_name)"
    if ! /opt/bin/python3 -c "import $import_name" 2>/dev/null; then
        log WARNING "Python库未安装: $library"
        return 1
    fi
    
    log INFO "Python库已安装: $library"
    return 0
}

# 安装Python库
install_python_library() {
    local library=$1
    
    log INFO "开始安装Python库: $library"
    
    # 确保pip已安装
    if ! command -v /opt/bin/pip3 >/dev/null 2>&1; then
        log INFO "安装python3-pip..."
        if ! /opt/bin/opkg install python3-pip; then
            log ERROR "python3-pip安装失败"
            return 1
        fi
    fi
    
    # 升级pip
    log INFO "升级pip..."
    if ! /opt/bin/pip3 install --upgrade pip; then
        log ERROR "pip升级失败"
        return 1
    fi
    
    # 安装指定库
    log INFO "安装$library库..."
    if ! /opt/bin/pip3 install "$library"; then
        log ERROR "$library库安装失败"
        return 1
    fi
    
    log INFO "$library库安装完成"
    return 0
}

# 检查Kodi远程控制是否开启
check_kodi_remote_control() {
    log INFO "检查Kodi远程控制设置..."
    
    if ! grep -q '<setting id="services.webserver">true</setting>' /storage/.kodi/userdata/guisettings.xml 2>/dev/null; then
        log WARNING "Kodi远程控制未开启"
        return 1
    fi
    
    log INFO "Kodi远程控制已开启"
    return 0
}

# 开启Kodi远程控制
enable_kodi_remote_control() {
    log INFO "开启Kodi远程控制..."
    
    if ! sed -i 's/<setting id="services.webserver">false<\/setting>/<setting id="services.webserver">true<\/setting>/' /storage/.kodi/userdata/guisettings.xml; then
        log ERROR "修改远程控制设置失败"
        return 1
    fi
    
    log INFO "Kodi远程控制已开启"
    return 0
}

# 检查autostart.sh配置
check_autostart_config() {
    log INFO "检查autostart.sh配置..."
    
    if ! grep -q "^/opt/bin/python3 /storage/autocover/main.py" "$AUTOSTART_FILE"; then
        log WARNING "autostart.sh未配置"
        return 1
    fi
    
    log INFO "autostart.sh已配置"
    return 0
}

# 配置autostart.sh
configure_autostart() {
    log INFO "配置autostart.sh..."
    
    if [ ! -f "$AUTOSTART_FILE" ]; then
        log INFO "创建新的autostart.sh文件"
        cat > "$AUTOSTART_FILE" <<EOF
#!/bin/sh
sleep 10
/opt/bin/python3 /storage/autocover/main.py &
EOF
        chmod +x "$AUTOSTART_FILE"
    else
        log INFO "修改现有autostart.sh文件"
        
        if ! grep -q "^#!/bin/sh" "$AUTOSTART_FILE"; then
            log WARNING "autostart.sh不以#!/bin/sh开头，添加..."
            sed -i '1i#!/bin/sh' "$AUTOSTART_FILE"
        fi
        
        sed -i '/sleep 10/d' "$AUTOSTART_FILE"
        sed -i '/\/opt\/bin\/python3 \/storage\/autocover\/main.py/d' "$AUTOSTART_FILE"
        sed -i "2i\\sleep 10\n/opt/bin/python3 /storage/autocover/main.py &" "$AUTOSTART_FILE"
    fi
    
    log INFO "autostart.sh配置完成"
    return 0
}

# 重启Kodi以重载皮肤
restart_kodi() {
    log INFO "准备重启Kodi以重载皮肤..."
    
    log INFO "重启Kodi服务..."
    echo -e "\033[34m正在重启Kodi以重载皮肤...\033[0m"
    
    if ! systemctl restart kodi.service; then
        log ERROR "重启Kodi服务失败"
        echo -e "\033[31m错误：重启Kodi失败，请手动重启Kodi以应用皮肤更改！\033[0m"
        return 1
    fi
    
    log INFO "等待Kodi重启..."
    sleep 3  # 等待Kodi重启完成
    
    log INFO "Kodi重启完成"
    echo -e "\033[32mKodi已重启，皮肤重载完成！\033[0m"
    return 0
}

# 检查所有依赖项
check_all_dependencies() {
    log INFO "开始全面依赖检查..."
    
    local missing_deps=0
    local dependency_list=""
    
    # 检查系统包
    log INFO "检查系统包依赖..."
    for package in $REQUIRED_PACKAGES; do
        if [ ! -x "$package" ] && [ ! -f "$package" ]; then
            log WARNING "缺少系统包: $package"
            missing_deps=1
            dependency_list="$dependency_list\n- $package"
        else
            log INFO "系统包已安装: $package"
        fi
    done
    
    # 检查Python库
    log INFO "检查Python库依赖..."
    for library in $REQUIRED_PYTHON_LIBS; do
        if ! check_python_library "$library"; then
            missing_deps=1
            dependency_list="$dependency_list\n- Python库: $library"
        fi
    done
    
    # 检查Kodi设置
    log INFO "检查Kodi设置..."
    if ! check_kodi_remote_control; then
        missing_deps=1
        dependency_list="$dependency_list\n- Kodi远程控制未开启"
    fi
    
    # 检查自动启动配置
    log INFO "检查自动启动配置..."
    if ! check_autostart_config; then
        missing_deps=1
        dependency_list="$dependency_list\n- 自动启动脚本未配置"
    fi
    
    # 返回检查结果
    if [ $missing_deps -eq 0 ]; then
        log INFO "所有依赖项均已满足"
        return 0
    else
        log WARNING "发现未满足的依赖项:$dependency_list"
        return 1
    fi
}

# 修复所有依赖项
fix_all_dependencies() {
    log INFO "开始修复依赖..."
    
    local errors=0
    
    # 配置镜像源
    configure_mirrors
    
    # 安装Entware
    if [ ! -x /opt/bin/opkg ]; then
        log INFO "需要安装Entware"
        if ! install_entware; then
            log ERROR "Entware安装失败"
            errors=1
        fi
    fi
    
    # 更新软件源
    if [ -x /opt/bin/opkg ]; then
        log INFO "更新软件源..."
        if ! /opt/bin/opkg update; then
            log ERROR "opkg更新失败"
            errors=1
        fi
    fi
    
    # 安装Python和pip
    if [ ! -x /opt/bin/python3 ]; then
        log INFO "需要安装Python3"
        if ! /opt/bin/opkg install python3; then
            log ERROR "Python3安装失败"
            errors=1
        fi
    fi
    
    # 安装Python库
    for library in $REQUIRED_PYTHON_LIBS; do
        if ! check_python_library "$library"; then
            log INFO "需要安装Python库: $library"
            if ! install_python_library "$library"; then
                log ERROR "Python库安装失败: $library"
                errors=1
            fi
        fi
    done
    
    # 开启Kodi远程控制
    if ! check_kodi_remote_control; then
        log INFO "需要开启Kodi远程控制"
        if ! enable_kodi_remote_control; then
            log ERROR "开启Kodi远程控制失败"
            errors=1
        fi
    fi
    
    # 配置自动启动
    if ! check_autostart_config; then
        log INFO "需要配置自动启动"
        if ! configure_autostart; then
            log ERROR "配置自动启动失败"
            errors=1
        fi
    fi
    
    # 返回修复结果
    if [ $errors -eq 0 ]; then
        log INFO "所有依赖项已成功修复"
        return 0
    else
        log ERROR "修复依赖项时发生错误"
        return 1
    fi
}

# 项目安装函数
install_project() {
    log INFO "开始项目安装..."
    
    # 创建项目目录
    mkdir -p "$PROJECT_DIR" || return 1
    
    # 下载Python脚本文件
    log INFO "下载Python脚本文件"
    download_file "main.py"
    download_file "generate_poster.py"
    download_file "get_kodi_info.py"
    download_file "download_posters.py"
    download_file "parse_playlist.py"
    
    # 创建必要的目录
    log INFO "创建项目子目录"
    mkdir -p "${PROJECT_DIR}/data" "${PROJECT_DIR}/temp" "${PROJECT_DIR}/output" "${FONT_PATH}"
    
    # 下载字体文件
    log INFO "下载字体文件..."
    download_file "ch.ttf" "${FONT_PATH}"
    download_file "en.otf" "${FONT_PATH}"
    
    # 检查关键文件是否下载成功
    if [ ! -f "$PYTHON_SCRIPT" ]; then
        log ERROR "Python主脚本下载失败"
        echo -e "\033[31m错误: Python主脚本下载失败！\033[0m"
        return 1
    fi
    
    # 检查字体文件是否下载成功
    missing_fonts=""
    for font in "${FONT_PATH}/ch.ttf" "${FONT_PATH}/en.otf"; do
        [ ! -f "$font" ] && missing_fonts="$missing_fonts $(basename "$font")"
    done
    if [ -n "$missing_fonts" ]; then
        log ERROR "字体文件下载失败: $missing_fonts"
        echo -e "\033[31m错误: 字体文件下载失败！缺失: $missing_fonts\033[0m"
        return 1
    fi
    
    log INFO "项目安装完成"
    return 0
}

# 下载文件辅助函数
download_file() {
    local file=$1
    local dest_dir=${2:-$PROJECT_DIR}
    local url="https://gitee.com/glsimon/auto-cover/raw/master/res/$file"
    
    if [ "$dest_dir" = "$FONT_PATH" ]; then
        url="https://gitee.com/glsimon/auto-cover/raw/master/fonts/$file"
    fi
    
    log INFO "下载 $file 到 $dest_dir"
    echo -e "\033[36m下载: $file\033[0m"
    
    if ! wget -qO "$dest_dir/$file" "$url"; then
        log WARNING "下载失败: $file，尝试备用源"
        if ! wget -qO "$dest_dir/$file" "https://raw.githubusercontent.com/glsimon/auto-cover/master/res/$file"; then
            log ERROR "下载失败: $file"
            echo -e "\033[31m下载失败: $file\033[0m"
            return 1
        fi
    fi
    
    return 0
}

# 皮肤修复处理
handle_skin_repair() {
    local skin=$1
    
    log INFO "开始处理皮肤修复: $skin"
    
    case $skin in
        skin.confluence.minsk)
            echo -e "\033[34m更新Confluence Minsk皮肤文件...\033[0m"
            mkdir -p /storage/.kodi/addons/skin.confluence.minsk/1080p || handle_error "创建皮肤目录失败"
            
            # 备份现有文件
            if [ -f /storage/.kodi/addons/skin.confluence.minsk/1080p/IncludesHomeMenuItems.xml ]; then
                log INFO "备份现有皮肤文件"
                cp /storage/.kodi/addons/skin.confluence.minsk/1080p/IncludesHomeMenuItems.xml \
                   /storage/.kodi/addons/skin.confluence.minsk/1080p/IncludesHomeMenuItems.xml.bak || handle_error "备份皮肤文件失败"
            fi
            
            # 下载新文件
            log INFO "下载皮肤文件"
            if ! wget -qO /storage/.kodi/addons/skin.confluence.minsk/1080p/IncludesHomeMenuItems.xml \
            "https://gitee.com/glsimon/auto-cover/raw/master/res/IncludesHomeMenuItems.xml"; then
                handle_error "下载皮肤文件失败"
            fi
            
            log INFO "Confluence Minsk皮肤修复完成"
            
            # 直接重启Kodi并显示提示
            echo -e "\n\033[33m正在重启Kodi以重载皮肤...\033[0m"
            if ! restart_kodi; then
                echo -e "\033[31m重启Kodi失败，请手动重启Kodi以应用皮肤更改！\033[0m"
            fi
            ;;
        *)
            log ERROR "暂不支持此皮肤的自动修复: $skin"
            echo -e "\033[31m暂不支持此皮肤的自动修复！\033[0m"
            return 1
            ;;
    esac
    return 0
}

# 主流程
main() {
    log INFO "脚本启动"
    
    # 检查依赖
    draw_interface
    echo -e "\033[33m[系统状态检测]\033[0m"
    
    if ! check_all_dependencies; then
        echo -e "\033[31m检测到未满足的依赖项！\033[0m"
        echo "1. 自动修复依赖"
        echo "2. 退出脚本"
        
        while true; do
            read -p "请输入选择: " choice
            
            case $choice in
                1)
                    draw_interface
                    echo -e "\033[34m正在修复依赖...\033[0m"
                    
                    if fix_all_dependencies; then
                        echo -e "\033[32m依赖修复完成！\033[0m"
                        # 创建依赖已安装标记
                        mkdir -p "$(dirname "$DEPENDENCY_MARKER")"
                        touch "$DEPENDENCY_MARKER"
                        sleep 2
                    else
                        echo -e "\033[31m依赖修复失败，请检查日志！\033[0m"
                        handle_error "依赖修复失败"
                    fi
                    break
                    ;;
                2)
                    log INFO "用户选择退出脚本"
                    exit 0
                    ;;
                *)
                    echo -e "\033[31m无效的选择，请重新输入！\033[0m"
                    ;;
            esac
        done
    else
        echo -e "\033[32m所有依赖项均已满足！\033[0m"
        # 创建依赖已安装标记
        mkdir -p "$(dirname "$DEPENDENCY_MARKER")"
        touch "$DEPENDENCY_MARKER"
        sleep 2
    fi
    
    # 安装项目
    draw_interface
    echo -e "\033[33m[项目安装]\033[0m"
    echo -e "\033[34m正在安装项目文件...\033[0m"
    
    if ! install_project; then
        handle_error "项目安装失败"
    fi
    
    echo -e "\033[32m项目安装完成！\033[0m"
    sleep 2
    
    # 主菜单循环
    while true; do
        draw_interface
        
        echo -e "\033[33m[可用皮肤列表]\033[0m"
        skin_list=$(find "/storage/.kodi/addons" -maxdepth 1 -type d -name 'skin.*' -exec basename {} \; | sort)
        
        count=0
        for skin in $skin_list; do
            index=$((++count))
            
            if echo "$SUPPORTED_SKINS" | tr ' ' '\n' | grep -Fxq "$skin"; then
                printf " \033[37m%2d.\033[0m %-28s \033[32m✅ 支持\033[0m\n" "$index" "$skin"
            else
                printf " \033[37m%2d.\033[0m %-28s \033[31m❌ 不支持\033[0m\n" "$index" "$skin"
            fi
        done
        
        printf " \033[37m%2d.\033[0m %-28s\n" 0 "退出"
        
        read -p $'\n\033[31m输入要修复的皮肤编号: \033[0m' choice
        
        [ "$choice" = "0" ] && {
            log INFO "用户选择退出脚本"
            break
        }
        
        if ! echo "$choice" | grep -qE "^[0-9]+$" || [ "$choice" -gt "$count" ]; then
            log WARNING "无效的编号: $choice"
            echo -e "\033[31m错误：无效的编号！\033[0m"
            sleep 1
            continue
        fi

        selected_skin=$(echo "$skin_list" | sed -n "${choice}p")
        
        if ! echo "$SUPPORTED_SKINS" | tr ' ' '\n' | grep -Fxq "$selected_skin"; then
            log WARNING "不支持的皮肤: $selected_skin"
            echo -e "\033[31m该皮肤暂不支持自动修复！\033[0m"
            sleep 2
            continue
        fi
        
        handle_skin_repair "$selected_skin"
        echo -e "\n按回车键继续..."
        read
    done
    
    clear
    log INFO "脚本正常退出"
}

# 执行主程序
main    